// packagePlayer/pages/music-player/index.js

import {
    audioContext,
    playerStore
} from '../../../store/index'

const playModeNames = ["order", "repeat", "random"]

Page({

    /**
     * 页面的初始数据
     */
    data: {
        id: 0,

        currentSong: {},
        durationTime: 0,
        lyricInfos: [],

        currentTime: 0,
        currentLyricIndex: 0,
        currentLyricText: "",

        isPlaying: false,
        playingName: "pause",

        playModeIndex: 0,
        playModeName: "order",

        isMusicLyric: true,
        currentPage: 0,
        contentHeight: 0,
        sliderValue: 0,
        isSliderChanging: false,
        lyricScrollTop: 0,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 1.获取传入的id
        const id = options.id || false
        // console.log(id)
        if (!id) {
            playerStore.dispatch('playMusicWithSongIdAction', {
                id: 1940943649
            })
        }
        this.setData({
            id
        })

        // 2.根据id获取歌曲信息
        this.setupPlayerStoreListener()

        // 3.动态计算内容高度
        const {
            screenHeight,
            statusBarHeight,
            navBarHeight,
            deviceRadio
        } = getApp().globalData
        const contentHeight = screenHeight - statusBarHeight - navBarHeight
        this.setData({
            contentHeight,
            isMusicLyric: deviceRadio >= 2
        })
    },

    // ========================   事件处理   ======================== 
    handleSwiperChange: function (event) {
        const current = event.detail.current
        this.setData({
            currentPage: current
        })
    },

    handleSliderChanging: function (event) {
        const value = event.detail.value
        const currentTime = this.data.durationTime * value / 100
        this.setData({
            isSliderChanging: true,
            currentTime
        })
    },

    handleSliderChange: function (event) {
        // 1.获取slider变化的值
        const value = event.detail.value

        // 2.计算需要播放的currentTIme
        const currentTime = this.data.durationTime * value / 100

        // 3.设置context播放currentTime位置的音乐
        audioContext.pause() // audioContext 需要先暂停, 系统bug, 后面用来其它的方法来进行优化
        audioContext.seek(currentTime / 1000)
        // playerStore.dispatch('changeTemp')
        // 4.记录最新的sliderValue, 并且需要讲isSliderChaning设置回false
        this.setData({
            sliderValue: value,
            isSliderChanging: false
        })
    },
    handleModeBtnClick: function () {
        // 计算最新的playModeIndex
        let playModeIndex = this.data.playModeIndex + 1
        if (playModeIndex === 3) playModeIndex = 0

        // 设置playerStore中的playModeIndex
        playerStore.setState("playModeIndex", playModeIndex)
    },
    handlePrevBtnClick: function () {
        playerStore.dispatch("changeNewMusicAction", false)
    },
    handlePlayBtnClick: function () {
        // 调用的是一个状态管理的工具
        playerStore.dispatch("changeMusicPlayStatusAction", !this.data.isPlaying)
    },
    handleNextBtnClick: function () {
        playerStore.dispatch("changeNewMusicAction")
    },

    handleBackBtnClick: function () {
        wx.navigateBack()
    },
    // ========================   数据监听   ======================== 
    handleCurrentMusicListener: function ({
        currentSong,
        durationTime,
        lyricInfos
    }) {
        if (currentSong) this.setData({
            currentSong
        })
        if (durationTime) this.setData({
            durationTime
        })
        if (lyricInfos) this.setData({
            lyricInfos
        })
    },

    setupPlayerStoreListener() {
        // 1.监听currentSong/durationTime/lyricInfos
        playerStore.onStates(["currentSong", "durationTime", "lyricInfos"], this.handleCurrentMusicListener)

        // 2.监听currentTime/currentLyricIndex/currentLyricText
        playerStore.onStates(["currentTime", 'currentLyricIndex', 'currentLyricText'], ({
            currentTime,
            currentLyricIndex,
            currentLyricText
        }) => {
            // 时间变化
            if (currentTime && !this.data.isSliderChanging) {
                const sliderValue = currentTime / this.data.durationTime * 100
                this.setData({
                    currentTime,
                    sliderValue
                })
            }
            // 歌词变化
            if (currentLyricIndex) {
                this.setData({
                    currentLyricIndex,
                    lyricScrollTop: currentLyricIndex * 35
                })
            }
            if (currentLyricText) {
                this.setData({
                    currentLyricText
                })
            }
        })

        // 3.监听播放模式相关的数据
        playerStore.onStates(["playModeIndex", "isPlaying"], ({
            playModeIndex,
            isPlaying
        }) => {
            if (playModeIndex !== undefined) {
                this.setData({
                    playModeIndex,
                    playModeName: playModeNames[playModeIndex]
                })
            }
            if (isPlaying !== undefined) {
                this.setData({
                    isPlaying,
                    playingName: isPlaying ? "pause" : "resume"
                })
            }
        })
    },
    onUnload: function () {
        playerStore.offStates(["currentSong", "durationTime", "lyricInfos"], this.handleCurrentMusicListener)
    },
})